
import { _decorator, Component, Sprite, lerp, assetManager, Input, EventTouch, Node, Prefab, instantiate, find, Label, macro, SpriteFrame, director, tween, resources } from "cc";
import { EDITOR } from "cc/env";
import { initData } from "./GameDefine";
import loskc from "./Script/SDK/loskc";
import { losChannel } from "./Script/SDK/losChannel";
import losPrivacyWin from "./Script/UI/losPrivacyWin";
import { _ui } from "../main/script/Main";
import { HuaWeiIdleMonitor } from "./Script/UI/HuaWeiIdleMonitor";
import { losChannelHw } from "./Script/SDK/losChannelHw";
import { losTools } from "./Script/Tools/losTools";

let isDoLoadingAnimation = false

// 加载主包
let isEnter = false;
(function () {
    if (EDITOR)
        return
    if (isEnter)
        return
    isEnter = true

    let _wx = (window as any)["wx"]
    if (_wx && _wx.startRenderDestroy)
        _wx.startRenderDestroy()

})();


// cc启动脚本
const { ccclass, property, menu } = _decorator;

@ccclass("App")
@menu("App")
export class App extends Component {

    private spriteRatio: Sprite = null!
    private ratio = 0

    @property({ type: Label })
    public ruanzhu: Label | null = null;
    @property({ type: Node })
    public node_age: Node | null = null;
    @property(losPrivacyWin)
    public privacyNode: losPrivacyWin | null = null

    @property({ type: Sprite })
    public logo: Sprite = null;

    @property({ type: [SpriteFrame] })
    /**
     * 0:合体吧块块 1:对号入球 2:球球去哪儿 3:球球传说
     */
    public logoSpriteFrame: SpriteFrame[] = [];

    @property(Label)
    public dialogLabel: Label = null;
    @property(Node)
    public dialogNode: Node = null;

    private _videoPlayTimes = 0;
    __preload() {

        // console.error("App.ts 进入 preload")

        let loading = this.node.getChildByName("Loading")!
        let ratio = loading.getChildByName("Ratio")!

        let ageButton = loading.getChildByName("Age")!
        ageButton.on(Input.EventType.TOUCH_END, (event: EventTouch) => {
            this.node_age.active = true;
        }, this);

        ratio.getChildByName("TopText")!.active = initData.showLoadingText

        // let dec = loading.getChildByName("BottomDec")!
        // if (initData.versionId && initData.showLoadingText) {
        //     dec.active = true
        //     dec.getComponentInChildren(Label)!.string = initData.versionId
        // }
        // else {
        //     dec.active = false
        // }
        losChannel.instance().init((code) => {

        });
        loading.getChildByName("Age")!.active = initData.showLoadingText

        this.spriteRatio = ratio.getChildByName("Bg")!.getComponentInChildren(Sprite)!

        this.updateRatio();
        loskc.init()

        this.logo.spriteFrame = this.logoSpriteFrame[3];
        (losChannel.instance().getChannel() as losChannelHw).qgLogin(() => {
            tween(this.spriteRatio).to(2, { fillRange: 1 }).call(() => {
                if (loskc.getData('isAgree', 0) == 0) {
                    resources.load('privacyWin', Prefab, (error, Prefab) => {
                        let node = instantiate(Prefab)
                        node.parent = find("UICanvas");
                    })
                } else {
                    this.loading();
                }
                //this.loading();
            }).start()
        }, () => {
            losTools.showLoginUI()
        })


    }
    protected onDisable(): void {
        this.unscheduleAllCallbacks()
    }
    protected onDestroy(): void {
        this.unscheduleAllCallbacks()
    }
    protected start() {
        this.ruanzhu.string = losChannel.instance().getChannel().ruanzhu
    }

    private updateRatio() {
        this.spriteRatio.fillRange = this.ratio
    }
    private loadProgress = 0;
    private _totalProgress = 2;
    protected update(dt: number): void {
        losChannel.instance().getChannel().doAction('loading中强弹视频', ['hw', this.spriteRatio.fillRange])
    }

    public loading() {
        console.log("load bundle main2 " + Date.now())
        assetManager.loadBundle("main2", (err, bundle) => {
            console.log('bundle main2 加载完成')
            loskc.log("sdk 初始化回调")
            //@ts-ignore
            let isKSMiniGame = typeof KSGameGlobal != 'undefined'
            if (isKSMiniGame) {
                //@ts-ignore
                console.log(GameGlobal)
                //@ts-ignore
                if (GameGlobal.__doInitCore) {
                    //@ts-ignore
                    GameGlobal.__doInitCore()
                }
                else {
                    console.log("window.__doInitCore 不存在")
                }
            }
            else {
                //@ts-ignore
                window.__doInitCore && window.__doInitCore()
            }



            loskc.log("游戏核心初始化 完成")
            /////////////////
            const channelName = losChannel.instance().channel


            HuaWeiIdleMonitor.inst.init();

            // losTools.showKuangDian(true)
            // else if (channelName == 'ks1') {
            // }
            // losTools.showRewardBoxNew()
        })
    }
    private _hwVideoPlayTimes = 0;
    private doPlayVideo() {
        if (this._hwVideoPlayTimes > 0) {
            losChannel.instance().showVideo({
                sucCall: () => { },
                failCall: () => { },
                endCall: () => {
                    this._hwVideoPlayTimes--;
                    this.doPlayVideo();
                }
            })
        }
    }

    private showDialog(code: number) {
        this.dialogNode.active = true;
        switch (code) {
            case 7004:
            case 2012:
                this.dialogLabel.string = '登录失败，请重新登录。';
                break;
            case 7021:
                this.dialogLabel.string = '需要实名认证才能进行游戏，请重新登录。';
                break;
            default:
                this.dialogLabel.string = `未知错误，错误码：${code}`;
                break;
        }
    }
    public onDialogConfirm() {
        this.dialogNode.active = false;
        losChannel.instance().login({
            successCall: async () => {
                if (!losChannel.instance().hasPrivacy()) {
                    console.error('隐私政策未同意，弹窗')
                    const privacy = find("UICanvas/privacyWinNode/privacyWin")
                    if (privacy) {
                        console.error('找到隐私政策节点，开始调用显示方法')
                        let privacyWinNode = privacy.getComponent(losPrivacyWin)
                        if (privacyWinNode) {
                            console.error('获取隐私政策脚本成功。')
                            const isAgree = await privacyWinNode.showAsyn()
                        }
                        else {
                            console.error('获取隐私政策脚本失败。')
                        }
                    }
                }
                isDoLoadingAnimation = true;
            },
            failCall: (code) => {
                this.showDialog(code);
            }
        })
    }
    public onDialogCancel() {
        losChannel.instance().exit();
    }
}